package funcs

import (
	"encoding/json"
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

// @BasePath		/api/v1
// PingExample		godoc
// @Summary			连接socket
// @Schemes
// @Description
// @Security 		Authorization
// @Tags 			socketServer
// @Accept			json
// @Produce			json
// @Router 			/ws/item [get]
func HandleWebSocket(c *gin.Context) {
	Rpc.Client.Call("Rpc.WsServer", c.Writer, c.Request)

	user_id := c.GetString("id")
	user_name := c.GetString("name")
	source := c.GetString("source")
	header := []string{
		c.GetHeader("Sec-Websocket-Protocol"),
	}
	// 决解跨域问题
	conn, err := (&websocket.Upgrader{
		CheckOrigin:  func(r *http.Request) bool { return true },
		Subprotocols: header,
	}).Upgrade(c.Writer, c.Request, nil)

	if err != nil {
		c.JSON(401, gin.H{"data": err.Error()})
		return
	}

	oldConn := FindUser(user_id, source)
	if oldConn != nil {
		oldConn.Socket.Close()
	}

	client := &Client{
		ID:       user_id,
		Socket:   conn,
		Send:     make(chan []byte),
		UserId:   user_id,
		Name:     user_name,
		Start:    time.Now(),
		IpSource: source,
	}

	Manager.Register <- client
	go client.Read()
	go client.Write()
}

// @BasePath		/api/v1
// PingExample		godoc
// @Summary			消息体
// @Schemes
// @Description
// @Security 		Authorization
// @Tags 			socketServer
// @Param			data	body	WsMessage	true	"消息结构"
// @Accept		json
// @Produce	json
// @Router 	/ws/sendMsg [post]
func PostMsg(c *gin.Context) {
	var revice WsMessage
	user_id := c.GetString("id")
	err := c.ShouldBind(&revice)
	if err != nil {

		c.JSON(401, gin.H{"data": "参数错误", "err": err.Error()})
	}

	conns := FindUsers(revice.UserId)
	for _, conn := range conns {
		resp, _ := json.Marshal(&WsMessage{Type: revice.Type, Data: revice.Data,
			Business: revice.Business, CallUrl: revice.CallUrl, UserId: user_id})

		conn.Send <- resp
	}

	if len(conns) == 0 {
		c.JSON(401, gin.H{"data": fmt.Sprintf(revice.UserId + `:用户不在线`)})
		return
	}
	c.JSON(200, gin.H{"data": "查找成功"})
}
